package com.elguile.laptop.baseDatos;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.elguile.laptop.entidades.Linea;
import com.elguile.laptop.entidades.Venta;

public class RepositorioVentaJdbc {

	private final DataSource dataSource;

	public RepositorioVentaJdbc(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public void agregarVenta(Venta venta) {
		Connection connection = null;
		try {
			connection = dataSource.getConnection();
			connection.setAutoCommit(false);
			PreparedStatement sentaciaAgregaVenta = connection
					.prepareStatement("insert into venta values");
			PreparedStatement sentaciaAgregaDetalle = connection
					.prepareStatement("insert into Detalleventa values");
			sentaciaAgregaVenta.setInt(1, venta.getCodigoVenta());
			sentaciaAgregaVenta.setDate(1, new java.sql.Date(venta
					.getFecha().getTime()));
			for (Linea linea : venta.getLineas()) {
				sentaciaAgregaDetalle.setInt(1, venta.getCodigoVenta());
				sentaciaAgregaDetalle.setString(1, linea.getDescripcion());
				sentaciaAgregaDetalle.setBigDecimal(2, linea.getPrecio());
			}
			connection.commit();
		} catch (SQLException e) {
			try {
				connection.rollback();
			} catch (SQLException e1) {
				throw new RuntimeException(e);
			}
			throw new RuntimeException(e);
		}
	}
}
